package edu.zjut.hjg.saas.kwmp.web.controller.home;

import static edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants.SESSION_NAME_USER;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.model.User;
import edu.zjut.hjg.saas.biz.service.UserService;
import edu.zjut.hjg.saas.common.annotation.CookieSessionOut;
import edu.zjut.hjg.saas.common.annotation.RequestAttribute;
import edu.zjut.hjg.saas.kwmp.web.model.UserSession;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/index.htm")
    public void index(
                      Model model,
                      @RequestParam(value = "toUrl", required = false) String toUrl,
                      @RequestHeader(value = "referer", required = false, defaultValue = "/index.htm") String referer) {
        if (toUrl == null) {
            toUrl = referer;
        }
        model.addAttribute("toUrl", toUrl);
    }

    @RequestMapping("/login.htm")
    @CookieSessionOut(SESSION_NAME_USER)
    public String login(
                        ModelMap model,
                        @RequestAttribute Kindergarten app,
                        @RequestParam("loginId") String loginId,
                        @RequestParam("password") String password,
                        @RequestParam(value = "toUrl", required = false, defaultValue = "/index.htm") String toUrl) {
        User user = userService.authenticate(app.getId(), loginId, password);
        if (user == null) {
            model.addAttribute("msgCode", "error.login.failed");
            model.addAttribute("loginId", loginId);
            model.addAttribute("toUrl", toUrl);
            return "login/index";
        }
        UserSession session = new UserSession();
        session.setId(user.getId());
        session.setLoginId(user.getLoginId());
        session.setName(user.getName());
        session.setRoleName(user.getRoleName());
        model.addAttribute(SESSION_NAME_USER, session);
        return "redirect:" + toUrl;
    }
}
